<?php

namespace Xrfg\Wallet\TRX\Jobs;

use App\Models\WtrcCollect;
use App\Models\Wtrx;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;
use Xrfg\Wallet\TRX\Services\TRXWallet;

class CollectJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public $coinName;
    public $wtrcCollect;

    public function __construct($coinName, WtrcCollect $wtrcCollect)
    {
        $this->coinName = $coinName;
        $this->wtrcCollect = $wtrcCollect;
    }

    public function handle()
    {
        try {
            logger('=====================collect transfer USDT-TRC20=====================');
            logger($this->wtrcCollect);
            DB::transaction(function () {
                $this->wtrcCollect = WtrcCollect::lockForUpdate()->find($this->wtrcCollect->id);
                if ($this->wtrcCollect->status == 1 && $this->wtrcCollect->hash == null) {
                    $txid = (new TRXWallet(config('wallet.trx.node.wallet')))->doTransferTRC20($this->coinName,$this->wtrcCollect->address,Wtrx::where('address',$this->wtrcCollect->address)->value('private_key'),config('wallet.trx.collect_address'),$this->wtrcCollect->number);
                    logger("txid:{$txid}");
                    if ($txid) {
                        $this->wtrcCollect->hash = $txid;
                        $this->wtrcCollect->save();
                    }
                }
            });
        } catch (Throwable $exception) {
            Log::error($exception);
        }
    }
}
